//
//  ImagePicker.swift
//  ModernFoodWebsite
//
//  Created by apple on 16/6/2.
//  Copyright © 2016年 Lonnie. All rights reserved.
//

import UIKit

class ImagePicker: NSObject,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    var finishHandler:([String:AnyObject])->Void = {(object) in}
    var cancelHandler:()->Void = {}
    var context:UIViewController
    init(context:UIViewController,complection:([String:AnyObject])->Void) {
        self.finishHandler = complection
        self.context = context
    }
    
    func pick() {
        let types = UIImagePickerController.isSourceTypeAvailable(.Camera) ? ["相机","相册"] : ["相册"]
        _ = UIAlertController(title: "选择图片", message: "", cancelTitle: "取消", otherTitles:types, context: self.context, complete:{(alert,index) in
            if index == 0 {
                return
            }
            let picker = UIImagePickerController()
            picker.delegate = self
            if index == 2 {
                picker.sourceType = .PhotoLibrary
            }
            else if index == 1 {
                picker.sourceType = .Camera
            }
            
            self.context.presentViewController(picker, animated: true, completion: nil)
            
        })
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        picker.dismissViewControllerAnimated(true, completion: nil)
        finishHandler(info)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
        cancelHandler()
    }
}